package docker_agent

import (
	"context"
	"strconv"

	"code.gitea.io/gitea/modules/log"
	devcontainer_service_errors "code.gitea.io/gitea/services/devstar_devcontainer/errors"
	devcontainer_service_options "code.gitea.io/gitea/services/devstar_devcontainer/options"
)

func AssignDevcontainerGettingDockerOperator(ctx *context.Context, opts *devcontainer_service_options.OpenDevcontainerAppDispatcherOptions) (uint16, error) {
	// 1. 创建docker client
	cli, err := CreateDockerClient(ctx)
	if err != nil {
		return 0, err
	}
	if cli != nil {
		defer cli.Close()
	}

	// 获取容器详细信息
	containerJSON, err := cli.ContainerInspect(context.Background(), opts.Name)
	if err != nil {
		return 0, err
	}

	// 获取端口映射信息
	portBindings := containerJSON.NetworkSettings.Ports
	for containerPort, bindings := range portBindings {
		for _, binding := range bindings {
			log.Info("Container Port %s is mapped to Host Port %s on IP %s\n", containerPort, binding.HostPort, binding.HostIP)
			if containerPort.Port() == "22" {
				v, err := strconv.ParseUint(binding.HostPort, 10, 16)
				if err != nil {
					return 0, err
				}
				return uint16(v), nil
			}

		}
	}
	return 0, devcontainer_service_errors.ErrOperateDevcontainer{
		Action:  "Open DevContainer in docker",
		Message: "cannot find SSH containerPort 22 for DevContainer " + opts.Name,
	}
}
